package tcpx

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"strconv"
	"sync/atomic"

	"std/netx"
)

type TcpTempX struct {
}

func (t TcpTempX) TcpClient(ii int) {
	conn, err := net.Dial("tcp", net.JoinHostPort(netx.Ip.String(), strconv.Itoa(netx.Port)))
	if err != nil {
		fmt.Println("err :", err)
		return
	}
	defer conn.Close()
	// write count> read count
	for i := 0; i < 20; i++ {
		msg := strconv.Itoa(ii) + `Hello,` + strconv.Itoa(i) + ";"
		conn.Write([]byte(msg))
	}
}
func (t TcpTempX) TcpServer() {
	listen, err := net.ListenTCP("tcp",
		&net.TCPAddr{
			IP:   netx.Ip,
			Port: netx.Port,
		},
	)
	if err != nil {
		fmt.Println("listen failed, err:", err)
		return
	}
	defer listen.Close()
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("accept failed, err:", err)
			continue
		}
		go t.process(conn)
	}
}
func (t TcpTempX) process(conn net.Conn) {
	defer conn.Close()
	reader := bufio.NewReader(conn)
	var buf [128]byte
	data := atomic.Int32{}

	for {
		n, err := reader.Read(buf[:])
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("read from client failed, err:", err)
			break
		}
		recvStr := string(buf[:n])
		fmt.Println("recv data:", data.Load(), recvStr)
		data.Add(1)
	}
}
